package org.zjx.db;

import com.alibaba.fastjson2.JSON;
import org.zjx.model.prop.ItemInstance;

import java.util.List;

public class ItemInstanceDB {
    private static boolean isTableCreated = false;
    private final SQLiteHelper dbHelper;

    public ItemInstanceDB() {
        dbHelper = SQLiteHelper.getSingleton();
        if (!isTableCreated) {
            createTable();
            isTableCreated = true;
        }
    }

    public void createTable() {
        String createTable = "CREATE TABLE IF NOT EXISTS item_instances (\n"
                + "    id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
                + "    name TEXT,\n"
                + "    playerId TEXT NOT NULL,\n"
                + "    templateId INTEGER NOT NULL,\n"
                + "    slotId INTEGER NOT NULL,\n"
                + "    stack INTEGER DEFAULT 1,\n"
                + "    durability INTEGER DEFAULT 1,\n"
                + "    durabilityEmptyDelete BOOLEAN DEFAULT 0,\n"
                + "    bound BOOLEAN DEFAULT 0,\n"
                + "    gather BOOLEAN DEFAULT 0,\n"
                + "    attributes TEXT,\n"
                + "    FOREIGN KEY(templateId) REFERENCES item_templates(id),\n"
                + "    FOREIGN KEY(slotId) REFERENCES item_slots(id)\n"
                + ");";
        dbHelper.createTable(createTable);
    }

    public void insert(ItemInstance instance) {
        String sql = "INSERT INTO item_instances(name, playerId, templateId, slotId, stack, "
                + "durability, durabilityEmptyDelete, bound, gather, attributes) "
                + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        Object[] params = {
                instance.getName(),
                instance.getPlayerId(),
                instance.getTemplateId(),
                instance.getSlotId(),
                instance.getStack(),
                instance.getDurability(),
                instance.isDurabilityEmptyDelete(),
                instance.isBound(),
                instance.isGather(),
                instance.getAttributes() != null && !instance.getAttributes().isEmpty()
                        ? JSON.toJSONString(instance.getAttributes())
                        : null
        };
        long generatedId = dbHelper.executeUpdate(sql, params);
        if (generatedId != -1) {
            instance.setId((int) generatedId);
        }
    }

    public void update(ItemInstance instance) {
        String sql = "UPDATE item_instances SET name = ?, playerId = ?, templateId = ?, slotId = ?, stack = ?, "
                + "durability = ?, durabilityEmptyDelete = ?, bound = ?, gather = ?, attributes = ? "
                + "WHERE id = ?";
        Object[] params = {
                instance.getName(),          // 新增 name 参数
                instance.getPlayerId(),
                instance.getTemplateId(),
                instance.getSlotId(),
                instance.getStack(),
                instance.getDurability(),
                instance.isDurabilityEmptyDelete(),
                instance.isBound(),
                instance.isGather(),
                instance.getAttributes() != null && !instance.getAttributes().isEmpty()
                        ? JSON.toJSONString(instance.getAttributes())
                        : null,
                instance.getId()
        };
        dbHelper.executeUpdate(sql, params);
    }

    public boolean update(List<ItemInstance> instances) {
        boolean success = true;
        for (ItemInstance instance : instances) {
            update(instance);
        }
        return success;
    }

    public void delete(int instanceId) {
        String sql = "DELETE FROM item_instances WHERE id = ?";
        Object[] params = {instanceId};
        dbHelper.executeUpdate(sql, params);
    }

    public ItemInstance findById(int instanceId) {
        String sql = "SELECT * FROM item_instances WHERE id = ?";
        Object[] params = {instanceId};
        List<ItemInstance> instances = dbHelper.executeQuery(sql, params, ItemInstance.class);
        return instances.isEmpty() ? null : instances.get(0);
    }

    public List<ItemInstance> findByPlayerId(String playerId) {
        String sql = "SELECT * FROM item_instances WHERE playerId = ?";
        Object[] params = {playerId};
        return dbHelper.executeQuery(sql, params, ItemInstance.class);
    }

    public List<ItemInstance> findBySlotId(int slotId) {
        String sql = "SELECT * FROM item_instances WHERE slotId = ?";
        Object[] params = {slotId};
        return dbHelper.executeQuery(sql, params, ItemInstance.class);
    }

    public List<ItemInstance> findByItemTemplateIdAndPlayerId(int itemTemplateId,String playerId) {
        String sql = "SELECT * FROM item_instances WHERE templateId = ? AND playerId = ?";
        Object[] params = {itemTemplateId,playerId};
        return dbHelper.executeQuery(sql, params, ItemInstance.class);
    }

    public List<ItemInstance> findAll() {
        String sql = "SELECT * FROM item_instances";
        return dbHelper.executeQuery(sql, null, ItemInstance.class);
    }

    public void clearData() {
        dbHelper.clearData("item_instances");
    }

    public void dropTable() {
        dbHelper.dropTable("item_instances");
    }
}